package com.siss.tenancy.user.utils;

import org.apache.commons.lang.reflect.FieldUtils;

import java.lang.reflect.Field;

/**
 * 类名: ReflectHelper.java
 * 描述: 对类及属性名称获取/设置属性对象
 * 创建人: yingw
 * 创建时间: 2018年7月5日上午9:25:40
 */
public class ReflectHelper {
	public static Object getFieldValue(Object obj , String fieldName ){  

        if(obj == null){  
            return null ;  
        }  

        Field targetField = getTargetField(obj.getClass(), fieldName);  

        try {  
            return FieldUtils.readField(targetField, obj, true ) ;  
        } catch (IllegalAccessException e) {  
            e.printStackTrace();  
        }   
        return null ;  
    }  

    public static Field getTargetField(Class<?> targetClass, String fieldName) {  
        Field field = null;  

        try {  
            if (targetClass == null) {  
                return field;  
            }  

            if (Object.class.equals(targetClass)) {  
                return field;  
            }  

            field = FieldUtils.getDeclaredField(targetClass, fieldName, true);  
            if (field == null) {  
                field = getTargetField(targetClass.getSuperclass(), fieldName);  
            }  
        } catch (Exception e) {  
        }  

        return field;  
    }  

    public static void setFieldValue(Object obj , String fieldName , Object value ){  
        if(null == obj){return;}  
        Field targetField = getTargetField(obj.getClass(), fieldName);    
        try {  
             FieldUtils.writeField(targetField, obj, value) ;  
        } catch (IllegalAccessException e) {  
            e.printStackTrace();  
        }   
    }   
}
